package data;

import java.sql.*;

public abstract class DataElement
{
    private boolean m_ExistsInData;
    private int m_ID;
    private DataFactory m_Factory;

    public DataFactory getFactory()
    {
	return m_Factory;
    }

    public String toString()
    {
        return "table=" + m_Factory.getTableName() + " id=" + getID() + " values=" + valuesString();
    }
	
	protected DataElement( DataFactory factory )
	{
		m_ExistsInData = false;
		m_Factory = factory;
	}
	
	public final int getID()
	{
		return m_ID;
	}
	
	public final void loadFrom( ResultSet rs )
	{
		m_ExistsInData = true;
		try {
			m_ID = rs.getInt( "id" );
			_loadFrom( rs );
		} catch( SQLException sqle ) {
			System.err.println( "SQL Error: " + sqle.getMessage() );
			sqle.printStackTrace();
			System.exit(1);
		}
	}
	
	public final void save()
	{
		String sql;
		String tableName = m_Factory.getTableName();
		
		if( m_ExistsInData ) {
			sql = "UPDATE " + tableName + " SET " + _update() + " WHERE id=" + m_ID; 
			
			// exec sql
			m_Factory.getDatabase().execUpdate( sql );
			
		} else {
			sql = "INSERT INTO " + tableName + _insert();
			
			m_ID = m_Factory.getDatabase().execInsert( sql, m_Factory.getKeySequence() );
		}
	}
	
	protected abstract String valuesString();
	protected abstract void _loadFrom( ResultSet rs ) throws SQLException;
	protected abstract String _insert();
	protected abstract String _update();
}
